/*
	连接管理模块实现
*/

package zserver

import (
	"errors"
	"fmt"
	"sync"
	"zinx/zinterface"
)

type ZConnManager struct {
	// 当前连接的集合
	connMap map[uint32]zinterface.IConnector

	connLock sync.RWMutex
}

func NewConnManager() zinterface.IConnManager {
	return &ZConnManager{
		connMap: make(map[uint32]zinterface.IConnector),
	}
}

// 实现IConnManager接口

// 1. 添加
func (zcm *ZConnManager) Add(conn zinterface.IConnector) {
	zcm.connLock.Lock()
	defer zcm.connLock.Unlock()

	zcm.connMap[conn.GetId()] = conn

	fmt.Println("[ZConnManager]: Add Conn: ", conn.GetId(), " | Conn Amount: ", len(zcm.connMap))
}

// 2. 删除
func (zcm *ZConnManager) Remove(conn zinterface.IConnector) {
	zcm.connLock.Lock()
	defer zcm.connLock.Unlock()

	delete(zcm.connMap, conn.GetId())
	
	fmt.Println("[ZConnManager]: Remove Conn: ", conn.GetId(), " | Conn Amount: ", len(zcm.connMap))
}

// 3. 查找
func (zcm *ZConnManager) Get(connId uint32) (zinterface.IConnector, error) {
	zcm.connLock.RLock()
	defer zcm.connLock.RUnlock()

	if conn, ok := zcm.connMap[connId]; ok {
		return conn, nil
	} else {
		return nil, errors.New("connection not found")
	}
}

// 4. 当前连接个数
func (zcm *ZConnManager) Len() int {
	return len(zcm.connMap)
}

// 5. 清理
func (zcm *ZConnManager) Clear() {
	zcm.connLock.Lock()
	defer zcm.connLock.Unlock()

	fmt.Println("[ZConnManager]: start clear conn")

	for connId, conn := range zcm.connMap {
		fmt.Println("[ZConnManager]: clear conn: ", connId)
		conn.Stop()
		delete(zcm.connMap, connId)
	}

	fmt.Println("[ZConnManager]: Clear finish, Conn Len: ", len(zcm.connMap))
}
